import sys
from math import cos, pi
from OCC.Core.BRepAlgoAPI import BRepAlgoAPI_Fuse
from OCC.Core.BRepFilletAPI import BRepFilletAPI_MakeFillet, BRepFilletAPI_MakeChamfer
from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeBox, BRepPrimAPI_MakeCylinder
from OCC.Display.SimpleGui import init_display
from OCC.Core.gp import gp_Pnt
from OCC.Extend.TopologyUtils import TopologyExplorer
from OCC.Core.TopTools import TopTools_IndexedMapOfShape
from OCC.Core.TopTools import TopTools_IndexedDataMapOfShapeListOfShape
import OCC.Core.TopAbs as TopAbs
from OCC.Core.TopExp import topexp_MapShapesAndAncestors,TopExp_Explorer
from OCC.Core.TopoDS import topods_Edge, topods_Face
from OCC.Core.BRep import BRep_Tool
# from part import Part
# from part_new import Part
import numpy as np
# display, start_display, add_menu, add_function_to_menu = init_display('wx')


class Rounding():

    def __init__(self,solid,r,index_list=None):
        self.solid = solid
        self.r = r
        self.fillet_ = BRepFilletAPI_MakeFillet(self.solid)
        self.index_list = index_list
        self.topology = TopologyExplorer(myShape=self.solid)
        self.shape_map = TopTools_IndexedMapOfShape()

    def edges_in(self):
        for e in self.topology.edges():
            self.shape_map.Add(e)

    def faces_in(self):
        for f in self.topology.faces():
            self.shape_map.Add(f)


    def fillet(self):
        if self.index_list is None:
            for e in TopologyExplorer(self.solid).edges():
                self.fillet_.Add(self.r,e)
        else:
            for index in self.index_list:
                e=self.shape_map.FindKey(index)
                self.fillet_.Add(self.r,e)

    def filleted_shape(self):
        self.edges_in()
        self.fillet()
        return self.fillet_.Shape()


class Chamfer():

    def __init__(self, solid, chamfer_detail=None):
        self.solid = solid
        self.chamfer = BRepFilletAPI_MakeChamfer(self.solid)
        self.chamfer_detail = chamfer_detail
        self.shape_map = TopTools_IndexedDataMapOfShapeListOfShape()

        self.topology = TopologyExplorer(myShape=self.solid)

    def fillet(self):
        topexp_MapShapesAndAncestors(self.solid, TopAbs.TopAbs_EDGE, TopAbs.TopAbs_FACE, self.shape_map)
        for chamfer in self.chamfer_detail:
            E = topods_Edge(self.shape_map.FindKey(chamfer['edge_id']))
            if chamfer['face']=="FIRST":
                F = topods_Face(self.shape_map.FindFromIndex(chamfer['edge_id']).First())
            elif chamfer['face']=="LAST":
                F = topods_Face(self.shape_map.FindFromIndex(chamfer['edge_id']).Last())
            self.chamfer.Add(chamfer['dis_1'], chamfer['dis_2'], E, F)

    def filleted_shape(self):
        self.fillet()
        return self.chamfer.Shape()






